package com.u2b.kvdb;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import com.sina.sae.storage.SaeStorage;

//?如何提高程序性能?
public class SaeFileHandler
{
    public HashMap<String, Object> saveToStorage(InputStream[] inputStreams, String[] fileTypes, String[] sqlKeys, String domain) throws IOException
    {
        SaeStorage storage = new SaeStorage();
        HashMap<String, Object> storagePaths = new HashMap<String, Object>();
        int length = inputStreams.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String currentTime = String.valueOf(System.currentTimeMillis());
        for (int i = 0; i < length; i++)
        {
            byte[] buffer = new byte[1024];

            String fileName = currentTime + fileTypes[i];
            int len = 0;
            while ((len = inputStreams[i].read(buffer)) != -1)
            {
                out.write(buffer, 0, len);
            }
            if (out.toByteArray().length > 0)
            {

                if (storage.write(domain, fileName, out.toByteArray()))
                    storagePaths.put(sqlKeys[i], "http://aweek-" + domain + ".stor.sinaapp.com/" + fileName);
            }
            else
            {
                storagePaths.put(sqlKeys[i], "0");

            }
            out.reset();// 重置,而不是重新new出来

        }

        return storagePaths;

    }

}
